package com.sibu.yx.promotion.admin.web.support.mvc;

import com.doubo.common.model.request.common.CommonRequest;
import com.doubo.common.threadlocal.SerialNo;
import com.sibu.yx.promotion.persistence.dto.UserPrincipal;
import org.apache.shiro.SecurityUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.util.List;

/**
 * @author suzheng
 * @date 2020-06-11
 **/
public class CustomRequestResponseBodyMethodProcessor extends RequestResponseBodyMethodProcessor {
    public CustomRequestResponseBodyMethodProcessor(List<HttpMessageConverter<?>> converters) {
        super(converters);
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(CustomRequestBody.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        Object target = super.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
        UserPrincipal userObj = (UserPrincipal) SecurityUtils.getSubject().getPrincipal();
        if (target instanceof CommonRequest) {
            //已登录的用户
            CommonRequest commonRequest = (CommonRequest) target;

            if(userObj != null){
                Object id = userObj.getUid();
                String currentUserId = id != null ? id.toString() : "";
                commonRequest.setCurrentUserId(currentUserId);
            }
            //SerialNo.init();//设置流水号
            commonRequest.setInitiationID(SerialNo.getSerialNo());
        }
        return target;
    }
}
